package xresponse

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/threading"
	"github.com/zeromicro/go-zero/rest/httpx"
	"maintenance/pkg/xjwt"
	"net/http"
	"time"
)

type Result struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data"`
}

func OkJsonCtx(r *http.Request, w http.ResponseWriter, req, resp any, err error) {
	var success int64
	if err != nil {
		httpx.ErrorCtx(r.Context(), w, err)
	} else {
		success = 1
		httpx.OkJsonCtx(r.Context(), w, wrapBaseResponse(resp))
	}
	// 写入日志
	ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
	threading.GoSafeCtx(ctx, func() {
		writeLog(ctx, nil, success, r, req, resp)
	})
}

func writeLog(ctx context.Context, tokenData *xjwt.TokenData, success int64, r *http.Request, req, resp any) {
	logx.Alert("write log")
}

func wrapBaseResponse(data any) *Result {
	return &Result{
		Code:    200,
		Message: "success",
		Data:    data,
	}
}
